<?php
/**
 * 购物车服务层
 * @author maniac
 */
namespace app\common\service;

use app\common\model\Buycar AS BuycarModel;
use app\common\model\WechatUsers;
use app\facade\Goods AS GoodsFacade;
use app\facade\GoodSpecs AS GoodSpecsFacade;
use app\facade\Stores AS StoresFacade;
use app\common\model\GoodSku AS GoodSkuModel;
use app\facade\Members AS MembersFacade;
use app\facade\Options AS OptionsFacade;

class Buycar extends Base
{
    /**
     * 加入购物车
     * @param array $data 请求的数据
     */
    public function add($data)
    {
        $where  = [
            'userid'       => $data['userid'],
            'goods_id'     => $data['goods_id'],
            'goods_sku_id' => $data['goods_sku_id'],
        ];
        $buycar_mod = new BuycarModel();
        $info = $buycar_mod->get_info($where,'id,goods_nums');
        if ($info) {
            $info->goods_nums = ['inc', $data['goods_nums']];
            $info->save();
            $id = $info['id'];
        } else {
            $buycar = BuycarModel::create($data);
            $id     = $buycar->id;
        }

        if ($id) {
            $result = $this->buycarList($data['userid'],'','');
            return $result;
        } else {
            exception('加入购物车失败');
        }
    }
    
    /**
     * 获取用户购物车列表
     * @param int $userId 用户 id
     * @param int $type 列表类型  0单商户 1多商户
     */
    public function buycarList($userId,$type = 0,$id)
    {
        $user = \app\common\model\Members::field('id')->where('id', $userId)->find();
        if (!$user) {
            exception('用户不存在');
        }
        $where = [];
        if(!empty($id)) {
            $where[] = ['id','in',$id];
        }
        $where[] = ['userid','eq',$userId];
        $buycar_mod = new BuycarModel();
        $buycar = $buycar_mod->getList($where,'','add_time DESC, id DESC');
        $data   = [];
        $goods_id= '';//商品ID
        $goodsku_id= '';//商品规格ID
        foreach ($buycar as $k => $v){
            $goods_id = $goods_id.','.$v['goods_id'];
            $goodsku_id = $goodsku_id.','.$v['goods_sku_id'];
        }
        $goods_mod = new \app\common\model\Goods();
        $goodsku_mod = new \app\common\model\GoodSku();
        $g_where = [
            ['id','in',$goods_id]
        ];
        $gs_where = [
            ['goods_id','in',$goods_id],
            ['sku_id','in',$goodsku_id],
        ];
        $goods_list = $goods_mod->getList($g_where,'','',array('goods_spec_format_array','image_uri'));
        $goodsku_list = $goodsku_mod->getList($gs_where);
        foreach ($buycar as $key => $val) {
            $sku = '';
            foreach ($goods_list as $gk => $gv){
                if($val['goods_id'] == $gv['id']){
                    $goods = $gv;
                }
            }
            foreach ($goodsku_list as $gsk => $gsv){
                if($val['goods_id'] == $gsv['goods_id'] && $val['goods_sku_id'] == $gsv['sku_id']){
                    $sku = $gsv;
                }
            }
            if ($sku) {
                // 存在商品 sku
                $val['sale_price'] = $sku['sale_price'];
                $val['stock']      = $sku['stock'];
                $val['goods_sku_id']      = $sku['id'];
                $val['image_uri']  = '';
                foreach ($goods['goods_spec_format_array'] as $k => $v) {
                    if (count($v['spec_value']) > 0) {
                        foreach ($v['spec_value'] as $k1 => $v1) {
                            if (strpos(';'.$sku['sku_id'].';', ';'.$v1['spec_id'].':'.$v1['spec_value_id'].';') !== false && isset($v1['spec_value_data']) && strpos($v1['spec_value_data'], 'https') !== false) {
                                $val['image_uri'] = $v1['spec_value_data'];
                                break;
                            }
                        }
                    }
                }
                $val['image_uri'] = $val['image_uri'] ?: $goods['image_uri'];
            } else {
                // 不存在商品 sku
                $val['sale_price'] = $goods['sale_price'];
                $val['stock']      = $goods['goods_stock'];
                $val['image_uri']  = $goods['image_uri'];
            }

            $val['goods_name']         = $goods['goods_name'];
            $val['min_purchase_nums']  = $goods['min_purchase_nums'] ?: 1;
            $val['max_purchase_nums']  = $goods['max_purchase_nums'] && $goods['max_purchase_nums'] < $val['stock'] ? $goods['max_purchase_nums'] : $val['stock'];
            $val['disabledMinusClass'] = $val['goods_nums'] == $val['min_purchase_nums'] ? ' m-disabled' : '';
            $val['disabledPlusClass']  = $val['goods_nums'] == $val['max_purchase_nums'] ? ' m-disabled' : '';
            $val['is_selected']        = true;
            $data[] = $val;
        }

        if($type == 1){//多商户购物车列表
            $buycar = BuycarModel::field('store_id')
                ->where('userid', $userId)->append(['store'])->group('store_id')->select()->toArray();
            $list = [];
            foreach ($buycar as $key =>$val){
				$val['list'] = array();
                foreach ($data as $k => $v){
                    if($val['store_id'] == $v['store_id']){
                        $val['list'][] = $v;
                    }
                }
                $list[] =$val;

            }

            $data = $list;
        }

        return $data;
    }




    /**
     * 编辑购物车商品
     * @param int $id        商品 id
     * @param int $goodsNums 商品数量
     */
    public function editCart($id, $goodsNums)
    {
        if ($goodsNums) {
            // 编辑
            BuycarModel::update([
                'id'         => $id,
                'goods_nums' => $goodsNums,
            ]);
        } else {
            // 删除
			
	    BuycarModel::destroy($id);
			

        }
        return true;
    }
}
